'use strict';
var path = require('path')
  , fs = require('fs')
  , _ = require('underscore')
  , UglifyJS = require("uglify-js")
  , gulp = require('gulp')
  , gutil = require('gulp-util')
  , eslint = require('gulp-eslint')
  , rimraf = require('rimraf')
  , webpack = require("webpack")
  ,	less = require('gulp-less')
  , cssnano = require('gulp-cssnano')
  , rev = require('gulp-rev')
  , revReplace = require('gulp-rev-replace')
  , server = require('gulp-develop-server')
  , webpackDevConfig = require('./webpack.dev')
  , webpackDistConfig = require('./webpack.dist')
  , lessDir = path.join(__dirname, 'style')
  , concat = require('gulp-concat')

gulp.task('clean-tmp',function(cb){
  rimraf('.tmp/',cb)
});

gulp.task('less-build',function(){

  gulp.src([lessDir+'/*.less','!'+lessDir+'/_*.less'])
    .pipe(less({
      paths: [
        path.join(__dirname, 'style')
      , path.join(__dirname, 'node_modules/')
      , path.join(__dirname, 'node_modules/fed-lib/less')
      ]
    }).on('error', function(e){
      gutil.log('[less]',gutil.colors.bold.red(e.message));
    }))
    .pipe(gulp.dest('.tmp/css/'));
});

gulp.task('webpack-build',function(cb){
  webpack(webpackDevConfig, function(err, stats) {
    if(err) throw new gutil.PluginError("webpack", err);
    cb();
  });
});


gulp.task('server',function(){
  server.listen( { path: 'index.js' } );
});

gulp.task('eslint',function(cb){
  return gulp.src(['modules/**/*.{js,jsx,es6}'])
    .pipe(eslint())
    .pipe(eslint.format())
})

gulp.task('clean-dist',function(cb){
  rimraf('dist/',cb)
});

gulp.task('less-dist',function(){

  gulp.src([lessDir+'/*.less','!'+lessDir+'/_*.less'])
    .pipe(less({
      paths: [
        path.join(__dirname, 'style')
      , path.join(__dirname, 'node_modules/')
      , path.join(__dirname, 'node_modules/fed-lib/less')
      ]
    }))
    .pipe(cssnano())
    .pipe(gulp.dest('dist/css/'));
});

gulp.task('webpack-dist',function(cb){
  webpack(webpackDistConfig, function(err, stats) {
    if(err) throw new gutil.PluginError("webpack", err);
    var assets = _(stats.toJson().assetsByChunkName).mapObject(function(name){
      return name.substring(0,name.length - 3)
    })
    gutil.log("[webpack]",JSON.stringify(assets, null, 2));
    var configContent = fs.readFileSync('config/config.js').toString()
      , requireJSContent = fs.readFileSync('node_modules/requirejs/require.js')
        .toString()
    fs.writeFileSync(
      'dist/js/bluewareui-seed.js'
      , UglifyJS.minify(requireJSContent, {fromString: true}).code
      + UglifyJS.minify(configContent, {fromString: true}).code.replace('paths:{}','paths:'+JSON.stringify(assets))
    )
    cb()
  });
});

gulp.task('copy-assets',function(){
  return gulp.src(['node_modules/fed-lib/assets/**','assets/**'])
    .pipe(gulp.dest('dist/'))
})
gulp.task('copy-freemarker',function(){
  return gulp.src('views/**')
    .pipe(gulp.dest('dist/freemarker/'))
})
gulp.task('iconfont-rev',['copy-assets'],function(){
  return gulp.src('dist/iconfont/**')
    .pipe(rev())
    .pipe(gulp.dest('dist/iconfont/'))
    .pipe(rev.manifest())
    .pipe(gulp.dest('dist/iconfont/'))
})
gulp.task('iconfont-replace',['less-dist','iconfont-rev'],function(){
  return gulp.src('dist/css/**')
    .pipe(revReplace({
      manifest:gulp.src('dist/iconfont/rev-manifest.json')
    }))
    .pipe(gulp.dest('dist/css/'))
})
gulp.task('serve',['clean-tmp'],function(){
  gulp.start('eslint','server')
})
gulp.task('compile',['clean-dist'],function(){
  gulp.start('less-build','webpack-build')
})
gulp.task('dist',['clean-dist'],function(){
  gulp.start('less-dist', 'webpack-dist', 'copy-assets', 'iconfont-rev', 'iconfont-replace','copy-freemarker');
})
